package com.ruan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruan.common.Code;
import com.ruan.common.R;
import com.ruan.common.Result;
import com.ruan.mapper.EmployeeMapper;
import com.ruan.mapper.ToolBorrowRecordsMapper;
import com.ruan.mapper.ToolsMapper;
import com.ruan.pojo.*;
import com.ruan.pojoExt.ToolBorrowRecordsExt;
import com.ruan.pojoExt.ToolsExt;
import com.ruan.service.*;
import com.ruan.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/toolBR")
public class ToolBorrowRecordsController {

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private ToolsService toolsService;

    @Autowired
    private ToolsMapper toolsMapper;

    @Autowired
    private ToolBorrowRecordsService toolBorrowRecordsService;

    @Autowired
    private ToolBorrowRecordsMapper toolBorrowRecordsMapper;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    PositionService positionService;


    /**
     * 获得待审核的工具借用列表
     * @return
     */
    @PostMapping("/getToolBR")
    public Result getToolBR() {
        LambdaQueryWrapper<ToolBorrowRecords> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(ToolBorrowRecords::getStatus,"待审核");
        List<ToolBorrowRecords> ToolBorrowRecordss = toolBorrowRecordsMapper.selectList(queryWrapper);


        List<ToolBorrowRecordsExt> ToolBorrowRecordsExtList = new ArrayList<>();
        for(ToolBorrowRecords ToolBorrowRecords : ToolBorrowRecordss){
            ToolBorrowRecordsExt ToolBorrowRecordsExt = new ToolBorrowRecordsExt();

            //属性迁移
            BeanUtils.copyProperties(ToolBorrowRecords, ToolBorrowRecordsExt);
            System.out.println("属性迁移完了吗1："+ToolBorrowRecordsExt);
            //查的是多人的待审核出差列表，所以名字要各自获得/\/\/\
            LambdaQueryWrapper<Employee> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(Employee::getId,ToolBorrowRecords.getEmployeeId());
            Employee employee = employeeMapper.selectOne(queryWrapper1);
            ToolBorrowRecordsExt.setEmployeeName(employee.getName());
            Position position = positionService.getById(employee.getPositionId());
            if(position != null) {
                ToolBorrowRecordsExt.setPosition(position.getPname());
            }
            ToolBorrowRecordsExt.setPhone(employee.getPhone());

            LambdaQueryWrapper<Tools> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(Tools::getId,ToolBorrowRecords.getToolId());
            Tools tool = toolsMapper.selectOne(queryWrapper2);
            if(tool != null) {
                ToolBorrowRecordsExt.setToolName(tool.getTname());
            }

            Department department = departmentService.getById(employee.getDepartmentId());

            if(department != null) {
            ToolBorrowRecordsExt.setDepartmentName(department.getName());
            }
            System.out.println("BcType是什么"+ToolBorrowRecords.getBcType());
            if(ToolBorrowRecords.getBcType().equals("consumed")){ //== "consumed"，在Java中，字符串比较应该使用equals()方法而不是==运算符
                //消耗没有归还时间没有借用时间
                System.out.println("进入消耗页");
                ToolBorrowRecordsExt.setReturnTime(null);
                ToolBorrowRecordsExt.setDay(null);
            }else{// if(ToolBorrowRecords.getBcType() == "borrowed"){
                System.out.println("进入借用页");
                System.out.println("没有归还时间吗："+ToolBorrowRecords.getReturnTime());
                //借用时有归还时间，可以计算借用天数
                // 创建两个时间对象
                Date date1 = Date.valueOf(String.valueOf(ToolBorrowRecords.getReturnTime()));
                Date date2 = Date.valueOf(String.valueOf(ToolBorrowRecords.getBorrowTime()));
                System.out.println(date1+"借用归还时间"+date2);
                // 计算两个时间之间的天数差异
                long diffInMillies = Math.abs(date2.getTime() - date1.getTime());
                long diffInDays = diffInMillies / (1000 * 60 * 60 * 24);
                ToolBorrowRecordsExt.setDay(Math.toIntExact(diffInDays));//计算借用天数
                System.out.println("借用时应该有借用天数："+ToolBorrowRecordsExt.getDay());
            }


            ToolBorrowRecordsExtList.add(ToolBorrowRecordsExt);
            System.out.println("ToolBorrowRecordsExtList是："+ToolBorrowRecordsExtList);
        }
        return new Result(Code.SAVE_OK,ToolBorrowRecordsExtList);
//        return ToolBorrowRecordsExt;
    }

    @PutMapping("/backAudit/{id}")///{adminId}
    public Result backAudit(@PathVariable Long id){//, @PathVariable Integer adminId
        try {
            String result = toolBorrowRecordsService.backAudit(id);//,adminId
            System.out.println("result是："+result);
            if(result == "工具归还申请成功"){
                return new Result(Code.UPDATE_OK,"工具归还申请成功！");
            }
            else {
                return new Result(Code.UPDATE_OK,"归还申请失败，请检查系统！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.UPDATE_ERR,"归还申请失败，请检查系统！");
        }

    }

    @PutMapping("/back/{id}/{adminId}")
    public Result back(@PathVariable Long id, @PathVariable Integer adminId){
        try {
            String result = toolBorrowRecordsService.back(id,adminId);
            System.out.println("result是："+result);
            if(result == "工具归还成功"){
                return new Result(Code.UPDATE_OK,"归还成功，已入库！");
            }
            else {
                return new Result(Code.UPDATE_OK,"归还失败，请检查系统！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.UPDATE_ERR,"归还失败，请检查系统！");
        }

    }

    @PutMapping("/refuseReturn/{id}/{adminId}")
    public Result refuseReturn(@PathVariable Integer id, @PathVariable Integer adminId){
        try {
            toolBorrowRecordsService.refuseReturn(id,adminId);
            return new Result(Code.UPDATE_OK,"归还审核成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.UPDATE_ERR,"归还审核失败，请检查系统！");
        }

    }

    @PutMapping("/agreed/{id}/{adminId}")
    public Result agreed(@PathVariable Integer id, @PathVariable Integer adminId){
        try {
            String result = toolBorrowRecordsService.agreed(id,adminId);
            System.out.println("result是："+result);
            if(result == "借用成功" || result == "消耗成功"){
                return new Result(Code.UPDATE_OK,"审核成功，已同意出库！");
             } else {
                return new Result(Code.UPDATE_OK,"库存不足，请检查库存！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.UPDATE_ERR,"审核失败，请检查系统！");
        }

    }

    @PutMapping("/refuse/{id}/{adminId}")
    public Result refuse(@PathVariable Integer id, @PathVariable Integer adminId){
        try {
            toolBorrowRecordsService.refuse(id,adminId);
            return new Result(Code.UPDATE_OK,"审核成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.UPDATE_ERR,"审核失败，请检查系统！");
        }

    }

    /**
     * 分页+条件 员工获取个人工具借用记录
     * @param currentPage 当前页
     * @param pageSize 每页最大数
     * @param querySelfAttendanceCondition 搜索条件
     * @return
     */
    @PostMapping("/getSelfToolsBR/{currentPage}/{pageSize}")
    public R<Page> getSelfToolsBR(@PathVariable int currentPage,
                                  @PathVariable int pageSize,
                                  @RequestBody QuerySelfAttendanceCondition querySelfAttendanceCondition) {

        Date month = querySelfAttendanceCondition.getMonth();//2024-2-1
        Page<ToolBorrowRecords> iPage=new Page<>(currentPage,pageSize);
        QueryWrapper<ToolBorrowRecords> queryWrapper = new QueryWrapper<>();
        //以审核状态为查询条件
        queryWrapper.eq(!querySelfAttendanceCondition.getStatus().equals(""),
                "status", querySelfAttendanceCondition.getStatus());

        LambdaQueryWrapper<Employee> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.like(Employee::getPhone, querySelfAttendanceCondition.getPhone());
        List<Employee> employeeList = employeeMapper.selectList(queryWrapper1);

        List<Long> employeeIds = employeeList.stream().map(Employee::getId).collect(Collectors.toList());
        queryWrapper.in("employee_id", employeeIds);//是QueryWrapper的技术语句
        if (month!=null){
            String firstDay = month.toString();//每月的第一天
            String lastDay = DateUtils.getLastDay(firstDay);//每月最后一天

            queryWrapper.between("submit_time",firstDay,lastDay);

            Page<ToolBorrowRecordsExt> iPageExt=new Page<>();//封装
            toolBorrowRecordsService.page(iPage,queryWrapper);//page方法已经已经继承了IService,已经提供了分页查询方法，只需要把Page对象和queryWrapper对象构造好，传给他，自己就会进行分页查询

            BeanUtils.copyProperties(iPage,iPageExt,"records");//从iPage一个一个拷贝属性到iPageExt上(除了records)
            List<ToolBorrowRecords> records = iPage.getRecords();
            List<ToolBorrowRecordsExt> list = records.stream().map((item) -> {//item:遍历出来的每一个项目对象
                ToolBorrowRecordsExt toolBorrowRecordsExt = new ToolBorrowRecordsExt();//只有EmployeeExt符合项目管理页面的要求，所以new一个出来,进行填充
                BeanUtils.copyProperties(item,toolBorrowRecordsExt);//先填充入employee的普通属性

                Long toolId = item.getToolId();//拿到了每个员工所对应的部门id
                Long employeeId = item.getEmployeeId();

                Employee employee = employeeService.getById(employeeId);
                Tools tool = toolsService.getById(toolId);

                if(employee != null){//能查到员工
                    toolBorrowRecordsExt.setEmployeeName(employee.getName());//填充入employee没有的employeeName属性
                    toolBorrowRecordsExt.setPhone(employee.getPhone());
                }
                Position position = positionService.getById(employee.getPositionId());
                if(position != null) {
                    toolBorrowRecordsExt.setPosition(position.getPname());
                }
                System.out.println("ReturnTime有值吗："+item.getReturnTime());
                if(item.getReturnTime() != null){
                    // 创建两个时间对象
                    Date date1 = Date.valueOf(String.valueOf(item.getReturnTime()));
                    Date date2 = Date.valueOf(String.valueOf(item.getBorrowTime()));
                    // 计算两个时间之间的天数差异
                    long diffInMillies = Math.abs(date2.getTime() - date1.getTime());
                    long diffInDays = diffInMillies / (1000 * 60 * 60 * 24);
                    toolBorrowRecordsExt.setDay(Math.toIntExact(diffInDays));//计算借用天数
                }
                if(item.getBcType().equals("consumed")){//消耗
                    toolBorrowRecordsExt.setToolStatus(0);//0已消耗，1,使用中，2,已归还
                }
                if(tool != null){
                    toolBorrowRecordsExt.setMfrs(tool.getMfrs());
                    toolBorrowRecordsExt.setPrice(tool.getPrice());
                    toolBorrowRecordsExt.setToolName(tool.getTname());
                    toolBorrowRecordsExt.setImage(tool.getImage());
                }
                //计算借到的工具的总价值
                int priceInt = tool.getPrice().intValue();
                int bnumInt = item.getBnum();
                toolBorrowRecordsExt.setSum(BigDecimal.valueOf(priceInt * bnumInt));

                return toolBorrowRecordsExt;//填充完新键的employeeExt之后，返回，把遍历的这些employeeExt对象搜集起来后
            }).collect(Collectors.toList());//就转成集合了，赋给List<EmployeeExt> list


            System.out.println("toolBorrowRecordsExt1里有了什么"+list);//.toString()
            iPageExt.setRecords(list);
            return R.success(iPageExt);
//            return new Result(Code.SELECT_OK,"查询个人工具借用记录成功！");
        }else {
            Page<ToolBorrowRecordsExt> iPageExt=new Page<>();//封装
            toolBorrowRecordsService.page(iPage,queryWrapper);//page方法已经已经继承了IService,已经提供了分页查询方法，只需要把Page对象和queryWrapper对象构造好，传给他，自己就会进行分页查询

            BeanUtils.copyProperties(iPage,iPageExt,"records");//从iPage一个一个拷贝属性到iPageExt上(除了records)
            List<ToolBorrowRecords> records = iPage.getRecords();
            List<ToolBorrowRecordsExt> list = records.stream().map((item) -> {//item:遍历出来的每一个项目对象
                ToolBorrowRecordsExt toolBorrowRecordsExt = new ToolBorrowRecordsExt();//只有EmployeeExt符合项目管理页面的要求，所以new一个出来,进行填充
                BeanUtils.copyProperties(item,toolBorrowRecordsExt);//先填充入employee的普通属性

                Long toolId = item.getToolId();//拿到了每个员工所对应的部门id
                Long employeeId = item.getEmployeeId();


                Employee employee = employeeService.getById(employeeId);
                Tools tool = toolsService.getById(toolId);

                if(employee != null){//能查到员工
                    toolBorrowRecordsExt.setEmployeeName(employee.getName());//填充入employee没有的employeeName属性
                    toolBorrowRecordsExt.setPhone(employee.getPhone());
                }
                Position position = positionService.getById(employee.getPositionId());
                if(position != null) {
                    toolBorrowRecordsExt.setPosition(position.getPname());
                }
                System.out.println("ReturnTime有值吗："+item.getReturnTime());

                if(item.getReturnTime() != null){
                    // 创建两个时间对象
                    Date date1 = Date.valueOf(String.valueOf(item.getReturnTime()));
                    Date date2 = Date.valueOf(String.valueOf(item.getBorrowTime()));
                    // 计算两个时间之间的天数差异
                    long diffInMillies = Math.abs(date2.getTime() - date1.getTime());
                    long diffInDays = diffInMillies / (1000 * 60 * 60 * 24);
                    toolBorrowRecordsExt.setDay(Math.toIntExact(diffInDays));//计算借用天数
                }

                if(tool != null){
                    toolBorrowRecordsExt.setMfrs(tool.getMfrs());
                    toolBorrowRecordsExt.setPrice(tool.getPrice());
                    toolBorrowRecordsExt.setToolName(tool.getTname());
                    toolBorrowRecordsExt.setImage(tool.getImage());

                    BigDecimal price = tool.getPrice();
                    Integer bnum = item.getBnum();
                    BigDecimal num = price.multiply(new BigDecimal(bnum));

                    toolBorrowRecordsExt.setSum(num);
                }
                return toolBorrowRecordsExt;//填充完新键的employeeExt之后，返回，把遍历的这些employeeExt对象搜集起来后
            }).collect(Collectors.toList());//就转成集合了，赋给List<EmployeeExt> list


            System.out.println("toolBorrowRecordsExt2里有了什么"+list);//.toString()
            iPageExt.setRecords(list);

            return R.success(iPageExt);
//            return new Result(Code.SELECT_ERR,"查询个人工具借用记录失败！");
        }
    }

    @DeleteMapping("/cancelToolApplication/{id}")
    public Result cancelToolApplication(@PathVariable Integer id){
        try {
            toolBorrowRecordsService.cancelToolApplication(id);
            return new Result(Code.DELETE_OK,"撤销工具出库申请成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.DELETE_ERR,"撤销工具出库申请失败！");
        }
    }

    @PostMapping("/appForToolBR")
    public Result appForResign(@RequestBody ToolBorrowRecords toolBR){
        try {
            Result result = toolBorrowRecordsService.appForToolBR(toolBR);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.SAVE_ERR,"提交失败！");
        }
    }

    //新增
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Tools tools){
        log.info("新增工具借用，工具信息：{}",tools.toString());
        toolsService.save(tools);//把这个对象存进去
//save方法继承自mybatis-plus的父接口IService（看看application.yml文件）,可以直接调用
        return R.success("新增工具信息成功");
    }

    @PostMapping("/updateTool")
    public Result updateTool(@RequestBody Tools tool){
        if (toolsService.updateById(tool)){
            return new Result(Code.UPDATE_OK,"修改成功！");
        }
        return new Result(Code.UPDATE_ERR,"修改失败！");
    }

}
